package com.pz.cloud.framework.society.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pz.cloud.framework.base.dao.CommonDao;
import com.pz.cloud.framework.base.expection.CustomRuntimeException;
import com.pz.cloud.framework.base.service.BaseServiceImpl;
import com.pz.cloud.framework.business.society.entity.OrgSociety;
import com.pz.cloud.framework.business.society.entity.OrgSocietyUser;
import com.pz.cloud.framework.business.society.service.IOrgSocietyService;
import com.pz.cloud.framework.business.society.service.IOrgSocietyUserService;
import com.pz.cloud.framework.business.stdGroup.entity.OrgStdGroup;
import com.pz.cloud.framework.business.student.entity.Student;
import com.pz.cloud.framework.business.workflow.annotation.Workflow;
import com.pz.cloud.framework.business.workflow.enums.WorkflowEnum;
import com.pz.cloud.framework.model.AbstractSqlBuilder;
import com.pz.cloud.framework.model.SqlBuilder;
import com.pz.cloud.framework.model.SqlQueryGenerator;
import com.pz.cloud.framework.society.callback.OrgSocietyUserCallback;
import com.pz.cloud.framework.society.mapper.OrgSocietyUserMapper;
import com.pz.cloud.framework.util.BeanUpdateUtils;
import com.pz.cloud.framework.util.BizUtil;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.handler.DataScopeHandler;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Description: 职务表
 * @Author: jeecg-boot
 * @Date: 2019-09-19
 * @Version: V1.0
 */
@Service
@Transactional
public class OrgSocietyUserServiceImpl extends BaseServiceImpl<OrgSocietyUserMapper, OrgSocietyUser> implements IOrgSocietyUserService {
    @Autowired
    private CommonDao commonDao;

    @Autowired
    private IOrgSocietyService orgSocietyService;

    @Autowired
    private ISysUserService sysUserService;

    @Workflow(callback = OrgSocietyUserCallback.class)
    public boolean save(OrgSocietyUser entity) {
        boolean flag ;
        if(StringUtils.isEmpty(entity.getId())){
            String societyId = entity.getSocietyId();
            if (StringUtils.isBlank(societyId)) {
                String societyName = entity.getSocietyName();
                if (StringUtils.isBlank(societyName)) {
                    throw new CustomRuntimeException("社团id和社团名称为空");
                }
                List<OrgSociety> societys = orgSocietyService.findByName(societyName);
                if (CollectionUtils.isEmpty(societys)) {
                    throw new CustomRuntimeException("该社团不存在");
                }
                societyId = societys.get(0).getId();
                entity.setSocietyId(societyId);
            }
            String userId = entity.getUserId();
            OrgSocietyUser orgSocietyUser = findByUserIdAndSocietyId(userId, societyId);
            if (orgSocietyUser != null) {
                throw new CustomRuntimeException("该用户申请中或已加入");
            }
            SysUser byId = sysUserService.getById(userId);
            if (byId == null) {
                throw new CustomRuntimeException("用户不存在");
            }
            entity.setRealname(byId.getRealname());
            flag = super.save(entity);
        }else{
            flag = super.updateById(entity);
        }
        OrgSociety orgSociety = orgSocietyService.getById(entity.getSocietyId());
        if(orgSociety!=null&&!StringUtils.isEmpty(orgSociety.getResponsibleManId())){
            entity.getWorkflowModel().setHandlerId(orgSociety.getResponsibleManId());
        }
        return flag;
    }

    @Override
    public IPage<OrgSocietyUser> findPage(OrgSocietyUser entity) {
        AbstractSqlBuilder sqlBuilder = sqlBuilder(entity);
        return commonDao.findPage(sqlBuilder);
    }

    @Override
    public IPage<OrgSocietyUser> findApplyPage(OrgSocietyUser entity) {
        AbstractSqlBuilder sqlBuilder = sqlBuilder(entity).append(" and (su.act_status in (").append(WorkflowEnum.ProcessStatus.流程中.getStatus().toString())
                .append(",").append(WorkflowEnum.ProcessStatus.流程退回.getStatus().toString()).append(") or (su.act_status=").append(WorkflowEnum.ProcessStatus.未开启.getStatus().toString())
                .append(" and su.user_id = :userId))").setParms("userId",BizUtil.getUserId());

        return commonDao.findPage(sqlBuilder);
    }

    @Override
    public OrgSocietyUser findByUserIdAndSocietyId(String userId, String societyId) {
        LambdaQueryWrapper<OrgSocietyUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrgSocietyUser::getUserId,userId);
        queryWrapper.eq(OrgSocietyUser::getSocietyId,societyId);
        return getOne(queryWrapper, false);
    }

    private AbstractSqlBuilder sqlBuilder(OrgSocietyUser entity) {
        AbstractSqlBuilder sqlBuilder = SqlBuilder.init("select su.*,s.name society_name,st.college,st.major,st.grade,st.clazz from ").append(entity.getTableName()).append(" su")
                .append(" inner join ").appendTable(OrgSociety.class).append(" s on su.society_id = s.id and s.del_flag = 0 ")
                .append(" left join ").appendTable(Student.class).append(" st on su.user_id = st.user_id and st.del_flag = 0 ")
                .append(" where s.act_status >= 10")//正式成立的组织
                .returnType(OrgSocietyUser.class)
                .page(entity)
                .orderBy("su.id desc")
                .joinCondition(entity, "su");
        //负责人可以看到组织内的数据
        DataScopeHandler dataScopeHandler = new DataScopeHandler()
                .setOrgSql("s.id in (select society_id from org_society_user where user_id = :userId and del_flag = 0 )").setOrgParms("userId",BizUtil.getUserId())
                .setPersonalSql("su.user_id = :userId ").setPersonalParms("userId",BizUtil.getUserId())
                .setCustomSql(" or s.id in (SELECT" +
                        " society_id FROM org_society_user" +
                        " WHERE user_id = :userId and del_flag = 0 and is_director = 1" +
                        ") ").setCustomParms("userId",BizUtil.getUserId());
        sqlBuilder.filterDataScope(dataScopeHandler);

        String societyName = entity.getSocietyName();
        if (StringUtils.isNotBlank(societyName)) {
            sqlBuilder.append(" and s.name like :societyName").setParmsLike("societyName", societyName);
        }
        return sqlBuilder;
    }
}
